package org.duncan.sjge.gamedata.sounds;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;

/**
 *
 * @author Duncan
 */
public class Sound {
    private Clip mClip;
    private long mStartTime;
    
    Sound(final File file) throws IOException, UnsupportedAudioFileException {
        try {
            final AudioInputStream sound = AudioSystem.getAudioInputStream(file);
            DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
            mClip = (Clip) AudioSystem.getLine(info);
            mClip.open(sound);
            
            mClip.addLineListener(new LineListener() {
                @Override
                public void update(LineEvent le) {
                    if (le.getType() == LineEvent.Type.STOP) {
                        mClip.setFramePosition(0);
                        mClip.stop();
                    }
                }
            });
        } catch (final LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }
    
    public void play() {
        mStartTime = System.currentTimeMillis();
        mClip.start();
    }
    
    public void stop() {
        mClip.stop();
    }
}
